package com.work.cloudseata.controller;

import cn.dev33.satoken.exception.NotLoginException;
import com.work.cloudseata.common.Ret;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionAdvice {

    @ExceptionHandler(NotLoginException.class)
    public Ret<Void> handleNoLoginException(NotLoginException e) {
        return Ret.fail(401, e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Ret<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        StringBuilder sb = new StringBuilder();
        for (ObjectError allError : e.getBindingResult().getAllErrors()) {
            sb.append(allError.getDefaultMessage()).append(";");
        }
        return Ret.fail(sb.toString());
    }

    @ExceptionHandler(Exception.class)
    public Ret<Void> handleException(Exception e) {
        log.error("未处理异常", e);
        return Ret.fail(e.getMessage());
    }
}
